package com.easy.generator;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * @author easy
 * @date 2025年07月05日 10:56
 */
public class ServiceGenerator  {


    public static void generate() throws Exception {
        // 获取类加载器
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        // 扫描包下的所有类
        Set<Class<?>> classes = scanClasses(Easy.BEAN_PACKAGE, classLoader);
        // 为每个实体类生成Controller
        for (Class<?> clazz : classes) {
            if (isEntityClass(clazz)) {
                generateServiceFile(clazz);
                generateServiceImplFile(clazz);
            }
        }
    }

    private static Set<Class<?>> scanClasses(String packageName, ClassLoader classLoader) throws Exception {
        Set<Class<?>> classes = new HashSet<>();
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (resource.getProtocol().equals("file")) {
                classes.addAll(findClasses(new File(resource.getFile()), packageName));
            }
        }
        return classes;
    }

    private static Set<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
        Set<Class<?>> classes = new HashSet<>();
        if (!directory.exists()) return classes;

        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                classes.add(Class.forName(className));
            }
        }
        return classes;
    }

    private static boolean isEntityClass(Class<?> clazz) {
        // 简单的实体类判断逻辑，可根据实际需求扩展
        return !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers());
    }

    private static void generateServiceFile(Class<?> entityClass) throws IOException {
        String className = entityClass.getSimpleName();
        String FileName = className + "Service";
        File dir = new File(Easy.PROJECT_ABSOLUTE_URL+"/src/main/java/" + Easy.SERVICE_PACKAGE.replace('.', '/'));
        if (!dir.exists()) {
            dir.mkdirs();}

        File file = new File(dir, FileName + ".java");
        try (PrintWriter out = new PrintWriter(file)) {
            String content="package "+Easy.SERVICE_PACKAGE+";\n" +
                    "\n" +
                    "import com.baomidou.mybatisplus.extension.service.IService;\n" +
                    "import "+Easy.BEAN_PACKAGE+"."+className+";\n" +

                    "public interface "+FileName+" extends IService<"+className+"> {\n" +
                    "}\n";

            out.println(content);

        }
    }

    private static void generateServiceImplFile(Class<?> entityClass) throws IOException {
        String className = entityClass.getSimpleName();
        String FileName = className + "ServiceImpl";
        File dir = new File(Easy.PROJECT_ABSOLUTE_URL+"/src/main/java/" + Easy.SERVICE_IMPL_PACKAGE.replace('.', '/'));
        if (!dir.exists()) {
            dir.mkdirs();}

        File file = new File(dir, FileName + ".java");
        try (PrintWriter out = new PrintWriter(file)) {
            String content="package "+Easy.SERVICE_IMPL_PACKAGE+";\n" +
                    "\n" +
                    "import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;\n" +
                    "import "+Easy.MAPPER_PACKAGE+"."+className+"Mapper;\n" +
                    "import "+Easy.BEAN_PACKAGE+"."+className+";\n" +
                    "import "+Easy.SERVICE_PACKAGE+"."+className+"Service;\n" +
                    "\n" +
                    "import org.springframework.stereotype.Service;\n" +
                    "\n" +
                    "@Service\n"+
                    "public class "+className+"ServiceImpl extends ServiceImpl<"+className+"Mapper,"+className+"> implements "+className+"Service {\n" +
                    "}\n";

            out.println(content);

        }
    }
}
